//
//  JPushManager.m
//  NewsReader
//
//  Created by Xiangxiang on 16/4/20.
//  Copyright © 2016年 GaoSir_. All rights reserved.
//

#import "JPushManager.h"
#import "JPUSHService.h"

@implementation JPushManager

+ (instancetype)shared{
    static JPushManager *shareManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [[JPushManager alloc] init];
    });
    return shareManager;
}

+ (void)jp_register:(NSDictionary *)launchOptions {
    if (IS_IOS8_OR_LATER) {
        [JPUSHService registerForRemoteNotificationTypes:UIUserNotificationTypeAlert |
                                              UIUserNotificationTypeBadge |
                                              UIUserNotificationTypeSound
                                              categories:nil];
    }else{
        [JPUSHService registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert |
                                              UIRemoteNotificationTypeBadge |
                                              UIRemoteNotificationTypeSound
                                              categories:nil];
    }
    
    [JPUSHService setupWithOption:launchOptions appKey:JPUSH_APPKEY channel:@"ios" apsForProduction:NO advertisingIdentifier:nil];
    [JPUSHService setLogOFF];
    //监听自定义消息
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(customMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

+ (void)jp_didRegister:(NSData *)deviceToken {
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}

+ (void)jp_enterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

+ (void)jp_didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
    //收到推送消息，进行处理
}

+ (void)jp_didReceiveLocalNotification:(UILocalNotification *)notification {
    //收到本地推送消息，进行处理
}

-(void)customMessage:(NSNotification *)notification {
    //收到自定义推送消息，进行处理
    NSDictionary *userInfo = [notification userInfo];
    
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        //app 前台，自定义提示UI
    }else{
        //app 后台，本地推送
        [JPUSHService setLocalNotification:[NSDate dateWithTimeIntervalSinceNow:2] alertBody:userInfo[@"content"] badge:1 alertAction:nil identifierKey:nil userInfo:nil soundName:nil];
    }
}

@end
